package com.luge.model.download;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.luge.base.Base;
import com.luge.model.download.DownLoad.DownLoadCallBack;

public class DownImageView extends ImageView {
	private Bitmap bitmap;
	private String urlPath;
	private String filePath;

	public DownImageView(Context context) {
		super(context);
	}

	public DownImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public DownImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public void loadImage(String urlSrc) {
		if (urlSrc == null || !urlSrc.contains(".")) {
			return;
		} else if (urlSrc.contains(Environment.getExternalStorageDirectory()
				.toString())) {
			try {
				bitmap = BitmapFactory.decodeFile(urlSrc);
				setImageBitmap(bitmap);
			} catch (OutOfMemoryError e) {

			}
		} else {
			this.urlPath = urlSrc;
			this.filePath = Base.cache_path
					+ urlPath
							.substring(urlPath.lastIndexOf("/") + 1,
									urlPath.length())
							.replace(Base.IMAGE_JPG, "")
							.replace(Base.IMAGE_PNG, "");
			DownLoadManager downLoadManager = DownLoadManager.getInstance();
			DownLoadCallBack callBack = new DownLoadCallBack() {

				@Override
				public void success(String urlSrc) {
					if (urlPath.equals(urlSrc)) {
						try {
							bitmap = BitmapFactory.decodeFile(filePath);
							setImageBitmap(bitmap);
						} catch (OutOfMemoryError e) {

						}
					}
				}

				@Override
				public void progress(int progress) {

				}

				@Override
				public void fail() {

				}
			};
			downLoadManager.add(urlPath, filePath, callBack);
		}
	}

	public void release() {
		if (bitmap != null) {
			setImageBitmap(null);
			bitmap.recycle();
			bitmap = null;
		}
	}

}
